package com.yifeng.repo.base.mdm.transport.impl;

import com.yifeng.base.account.api.dto.AdmOrgCoreInfoDto;
import com.yifeng.base.account.api.param.AdmOrgParam;
import com.yifeng.repo.base.api.DateTimeRange;
import com.yifeng.repo.base.constant.BaseConstant;
import com.yifeng.repo.base.mdm.MasterDataManager;
import com.yifeng.repo.base.mdm.transport.biz.BizTransportAction;
import com.yifeng.repo.base.utils.converter.DateHelper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by daibing on 2024/2/7.
 */
@Slf4j
public class DefaultAdmOrgTransportAction implements BizTransportAction<AdmOrgCoreInfoDto> {
    private static final String OFFSET_START_TIME = "offsetStartTime";
    private static final String OFFSET_ORG_CODE = "offsetOrgCode";

    @Override
    public List<AdmOrgCoreInfoDto> fetchData(String segmentKey, DateTimeRange dateTimeRange, Map<String, Object> offsetMap,
                                             MasterDataManager masterDataManager) {
        AdmOrgParam param = new AdmOrgParam();
        param.setEnable(Boolean.TRUE);
        param.setEndTime(dateTimeRange.getEnd());
        param.setOffsetStartTime(offsetMap.containsKey(OFFSET_START_TIME)
                ? DateHelper.parseDateTime(offsetMap.get(OFFSET_START_TIME).toString()) : dateTimeRange.getStart());
        param.setOffsetOrgCode(offsetMap.containsKey(OFFSET_ORG_CODE) ? offsetMap.get(OFFSET_ORG_CODE).toString() : null);
        param.setPageSize(BaseConstant.CORE_BATCH_SIZE_LIMIT);
        return masterDataManager.getAdmOrgMasterDataRestService().listCoreInfo(param);
    }

    @Override
    public Map<String, Object> saveData(String segmentKey, List<AdmOrgCoreInfoDto> dataList) {
        // 处理结果数据
        String names = dataList.stream().map(s -> s.getOrgShortName() + s.getStoreCode()).collect(Collectors.joining(","));
        log.info("admOrg result: segmentKey={}, size={}, names={}", segmentKey, dataList.size(), names);

        // 设置偏移量
        AdmOrgCoreInfoDto last = dataList.get(dataList.size() - 1);
        Map<String, Object> offsetMap = new HashMap<>(2);
        offsetMap.put(OFFSET_START_TIME, DateHelper.getDateTime(last.getModifyTime()));
        offsetMap.put(OFFSET_ORG_CODE, last.getOrgCode());
        return offsetMap;
    }

    @Override
    public void finished(String segmentKey, DateTimeRange dateTimeRange, Integer count) {
        log.info("admOrg transport ok, segmentKey={}, statStartTime={}, statEndTime={}, count={}",
                segmentKey, dateTimeRange.getStart(), dateTimeRange.getEnd(), count);
    }
}
